package scm_clients

import (
	"context"

	"gitee.com/xmwilldo/gitee_client"
	"github.com/antihax/optional"
	"github.com/drone/drone-go/drone"
	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
	"golang.org/x/oauth2"
)

type GiteeClient struct {
	delegate *gitee_client.APIClient
	repo     drone.Repo
}

func NewGiteeClient(someUUID uuid.UUID, token string, repo drone.Repo) (ScmClient, error) {
	var client *gitee_client.APIClient
	var err error

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)

	conf := gitee_client.NewConfiguration()
	conf.HTTPClient = oauth2.NewClient(context.Background(), ts)
	logrus.Infof("%s Created gitee API client", someUUID)

	client = gitee_client.NewAPIClient(conf)
	return &GiteeClient{
		delegate: client,
		repo:     repo,
	}, err

}

func (l GiteeClient) ChangedFilesInPullRequest(ctx context.Context, pullRequestID int) ([]string, error) {
	logrus.Warnf("pull request not implemente")
	return []string{}, nil
}

func (l GiteeClient) ChangedFilesInDiff(ctx context.Context, base string, head string) ([]string, error) {
	logrus.Infof("ChangedFilesInDiff, base:%s, head:%s", base, head)
	logrus.Debugf("repo: %+v", l.repo)

	compare, _, _ := l.delegate.RepositoriesApi.GetV5ReposOwnerRepoCompareBaseHead(context.TODO(), l.repo.Namespace, l.repo.Name, base, head, nil)
	if len(compare.Files) == 0 {
		logrus.Warnf("files in diff len is 0")
		return nil, nil
	}
	files := make([]string, 0)
	for _, file := range compare.Files {
		files = append(files, file.Filename)
	}

	return files, nil
}

func (l GiteeClient) GetFileContents(ctx context.Context, path string, commitRef string) (fileContent string, err error) {
	content, _, err := l.delegate.RepositoriesApi.GetV5ReposOwnerRepoRawPath(ctx, l.repo.Namespace, l.repo.Name, path, &gitee_client.RepositoriesApiGetV5ReposOwnerRepoRawPathOpts{
		Ref: optional.NewString(commitRef),
	})
	if err != nil {
		return "", err
	}

	return string(content), nil
}

func (l GiteeClient) GetFileListing(ctx context.Context, path string, commitRef string) (fileListing []FileListingEntry, err error) {
	contents, _, _ := l.delegate.RepositoriesApi.GetV5ReposOwnerRepoContentsPath(ctx, l.repo.Namespace, l.repo.Name, path, &gitee_client.RepositoriesApiGetV5ReposOwnerRepoContentsPathOpts{
		Ref: optional.NewString(commitRef),
	})

	if len(contents) == 0 {
		logrus.Warnf("get repo contents len is 0")
		return nil, nil
	}

	fileListing = make([]FileListingEntry, 0)
	for _, content := range contents {
		fileListing = append(fileListing, FileListingEntry{
			Type: content.Type_,
			Name: content.Name,
			Path: content.Path,
		})
	}

	return fileListing, nil
}
